package com.wenbo.fish.service.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.wenbo.fish.entity.SpiderInfo;
import com.wenbo.fish.enums.SpiderServiceEnum;
import com.wenbo.fish.service.AbstractSpiderService;
import com.wenbo.fish.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author changwenbo
 * @date 2024/12/31 14:42
 */
@Service
public class TouTiaoSpiderServiceImpl extends AbstractSpiderService {
    private static final Logger log = LoggerFactory.getLogger(TouTiaoSpiderServiceImpl.class);

    @Override
    protected List<SpiderInfo> parseData(String body) {
        try {
            JsonObject jsonObject = GsonUtils.parseWithNullable(body);
            JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();

            List<SpiderInfo> list = new ArrayList<>();
            for (JsonElement jsonElement : jsonArray) {
                JsonObject object = jsonElement.getAsJsonObject();
                SpiderInfo spiderInfo = new SpiderInfo(GsonUtils.getValue(object, "Title"), GsonUtils.getValue(object, "Url"));
                list.add(spiderInfo);
            }

            return list;
        } catch (Exception e) {
            log.error("TouTiaoSpiderServiceImpl parseData error e = {}", e.getMessage(), e);
        }

        return EMPTY_LIST;
    }

    @Override
    public SpiderServiceEnum getServiceName() {
        return SpiderServiceEnum.TOU_TIAO;
    }

}
